<?php
namespace Home\Controller;
use Think\Controller;
use Think\Verify;
class IndexController extends Controller {
    public function index(){
        header("Content-Type: text/html;charset=utf-8");

        // echo session_id();
        // die();


        //1 查谒表是否已经登录，已经登录，直接进入
        //2 session_id()不同的话，判断登录时间，超过24分钟后，重新登录，没超过，提示已经在其它设备登录，是否重新登录，重新登录，其它设备将下线。
        //3 登录信息写入缓存
        //$ip=$_SERVER["REMOTE_ADDR"];
       // $login=array();
       // $login[0]=array('userid'=>session('userid'),
            //'login_time'=>time(),'session_id'=>session_id(),'login_ip'=>$ip);
       // $login[1]=array('userid'=>session('userid'),
            //'login_time'=>time(),'session_id'=>session_id(),'login_ip'=>$ip);
//        $userid=1;
//        $islogin=false;
//        F('login');
//        foreach(F('login') as $vo)
//        {
//            if($vo['userid']==$userid)
//            {
//                $islogin=true;
//                if($vo['session_id']!=session_id())
//                {
//                    if($vo['login_time']+24*60>time())// 登录时间没过期
//                    {
//                        echo '用户已经在其它设备登录，是否重新登录？';
//                        die();
//                    }
//                    else
//                    {
//                        break;
//                    }
//                }
//                else
//                {
//                    break;
//                }
//            }
//        }
//
//        if($islogin==false)
//        {
//            $count=count(F('login'));
//            $data=F('login');
//            $data[$count]=array('userid'=>$userid,'session_id'=>session_id(),'login_time'=>time());
//            F('login',$data);
//        }
//        die();

//        \Predis\Autoloader::register();
//        $a = new \Predis\Client();
//        $a->set('fgl','<br>redis缓存设置了');
//        echo $a->get('fgl');
//
       //phpinfo();
//
        // die();
//        $redis = new \Redis();
//        $redis->connect('127.0.0.1',6379);
//        $redis->set('test','hello world!');
//        echo $redis->get("test");
//
//        die();

        $username=I('get.u');
        $code=I('get.v');
        $this->assign('username',$username);
        $this->assign('code',$code);
        $T=M('setting');
        $tdata=$T->where('id=1')->find();
        if($tdata['web_config']==1)
        {
          
            echo'系统正在升级中，请稍候再访问，为此对您造成不便，敬请原谅！';
            die();
        }
        //超过12小时不打款，冻结帐户
        //$this->offuser();

        $this->display();
     }
    //用户登录
    public function dologin(){

        header("Content-Type: text/html;charset=utf-8");
        $username=I('post.username');
        $password=I('post.password');
        //检测验证码
        $code = I('post.verify');
        if(!$this->check_verify($code, ''))
        {

            echo"<script>alert('输入的验证码有误，请重新输入！');location.href='/?u=".$username."&v=".$code."'</script>";
            exit;
        }
        if(!empty($username)){

            $data['username'] = $username;
            $password = md5($password);
            $admin = M('user');
            $info = $admin->where("(username='".$data['username']."' or mobile='".$username."') and password = '".$password."'")->find();
          


            if(!empty($info))
            {


                if($info['status']==3)
                {


                    echo"<script>alert('帐户已经被冻结，如有疑问请联系客服，谢谢！');location.href='/?u=".$username."&v=".$code."'</script>";
                    die();

                }
                if($info['status']==0)
                {


                    echo"<script>alert('帐户还没有开通，请联系推荐人开通后再登录，谢谢！');location.href='/?u=".$username."&v=".$code."'</script>";
                    die();

                }
                //elseif($info['status']==0)
                //{


                   // echo"<script>alert('帐户还没有通过审核！请联系客服进行审核！');history.go(-1);</script>";
                   // die();

                //}
                $data=F('login');

                if(!empty($data)){
                    $islogin=false;
                    foreach(F('login') as $vo)
                    {
                        if($vo['userid']==$info['id'])
                        {
                            $islogin=true;
                            if($vo['session_id']!=session_id())
                            {
                                if($vo['login_time']+24*60>time())// 登录时间没过期
                                {
                                    echo '用户已经在其它设备登录，是否重新登录？';
                                    die();
                                }
                                else
                                {
                                    break;
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                    }

                    if($islogin==false)
                    {
                        $count=count(F('login'));
                        $data=F('login');
                        $data[$count]=array('userid'=>$info['id'],'session_id'=>session_id(),'login_time'=>time());
                        F('login',$data);
                    }
                }
                else
                {
                    $data[0]=array('userid'=>$info['id'],'session_id'=>session_id(),'login_time'=>time());
                    F('login',$data);
                }



                session('userid',$info['id']);
                session('username',$info['username']);
                session('status',$info['status']);//0  未开通，１已开通　２休眠　３冻结　
                session('limit',$info['limit']);//投资额度
                session('fire',$info['fire']);//是否烧伤0 不烧伤，１烧伤
                session('logintime',time());//登录时间




                //系统初始设置
                //$this->Setting();
                //$this->TaskAutoClose();//定时自动删除

                redirect('/user/');

                //echo "<script>window.parent.location.reload();<//script>";
                //echo "<script>window.parent.Windows.openApp(2,\"个人中心\",\"/home/user/index\",\"user.png\",\"\",1100,500);window.parent.Windows.closeElseWindow(2);<//script>";
            }
            else
            {

                //$this->error('用户帐户或者密码有误，请重新输入','/',2);
                echo"<script>alert('用户帐户或者密码有误，请重新输入');location.href='/?u=".$username."&v=".$code."'</script>";
                die();
            }
            exit;
        }else{

            echo"<script>alert('会员帐户为空，请重新输入');location.href='/?u=".$username."&v=".$code."'</script>";
            die();
        }
    }

    public function dologinajax(){


        $username=I('post.username');
        $password=I('post.password');
        $login=I('post.login');


       if($login==0)
       {
        //检测验证码
        $code = I('post.verify');
        if(!$this->check_verify($code, ''))
        {

            echo 5;
            die();
        }
       }
        if(!empty($username)){

            $data['username'] = $username;
            $password = md5($password);
            $admin = M('user');
            $info = $admin->where("(username='".$data['username']."' or mobile='".$username."') and password = '".$password."'")->find();



            if(!empty($info))
            {


                if($info['status']==3)
                {


                    echo 3;
                    die();

                }
                if($info['status']==0)
                {


                    echo 4;
                    die();

                }
                //elseif($info['status']==0)
                //{


                // echo"<script>alert('帐户还没有通过审核！请联系客服进行审核！');history.go(-1);</script>";
                // die();

                //}

                if($login==0)
                {


                    $data=F('login');
                    if(!empty($data)){

                        $islogin=false;
                        foreach(F('login') as $vo)
                        {
                            if($vo['userid']==$info['id'])
                            {

                                $islogin=true;
                                if($vo['session_id']!=session_id())
                                {
                                    if($vo['login_time']+24*60>time()) {
                                        echo '6';
                                        die();
                                    }
                                    else
                                    {
                                        break;
                                    }

                                }
                                else
                                {
                                    break;
                                }
                            }
                        }

                        if($islogin==false)
                        {
                            $count=count(F('login'));
                            $data=F('login');
                            $data[$count]=array('userid'=>$info['id'],'session_id'=>session_id(),'login_time'=>time());
                            F('login',$data);
                        }
                    }
                    else
                    {
                        $data[0]=array('userid'=>$info['id'],'session_id'=>session_id(),'login_time'=>time());
                        F('login',$data);
                    }
                }

                else
               {
                    //替换Session_id值
                    $data=F('login');
                    foreach(F('login') as $key=>$vo) {
                        if($vo['session_id']!=session_id())
                        {
                            $data[$key]['session_id']=session_id();
                            $data[$key]['login_time']=time();
                        }
                    }
                    F('login',$data);
                }

                session('admin_login',0);
                session('userid',$info['id']);
                session('username',$info['username']);
                session('status',$info['status']);//0  未开通，１已开通　２休眠　３冻结　
                session('limit',$info['limit']);//投资额度
                session('fire',$info['fire']);//是否烧伤0 不烧伤，１烧伤
                session('logintime',time());//登录时间

                echo 1;
                die();


                //系统初始设置
                //$this->Setting();
                //$this->TaskAutoClose();//定时自动删除

                //redirect('/user/');

                //echo "<script>window.parent.location.reload();<//script>";
                //echo "<script>window.parent.Windows.openApp(2,\"个人中心\",\"/home/user/index\",\"user.png\",\"\",1100,500);window.parent.Windows.closeElseWindow(2);<//script>";
            }
            else
            {

                //$this->error('用户帐户或者密码有误，请重新输入','/',2);
                echo 2;
                die();
            }
            exit;
        }else{

            //echo"<script>alert('会员帐户为空，请重新输入');location.href='/?u=".$username."&v=".$code."'</script>";
            //die();
        }
        echo 1;
        die();
    }
    public function verify(){
        ob_clean();
        $Verify = new \Think\Verify();
        $Verify->fontSize = 16;
        $Verify->length   = 4;
        $Verify->useNoise = false;
        $Verify->codeSet = '0123456789';
        $Verify->imageW = 120;
        $Verify->imageH = 40;
        //$Verify->expire = 600;
        $Verify->entry();


    }
    //检测验证码
    public function check_verify($code, $id = ''){
        $verify = new Verify();
        return $verify->check($code, $id);
    }
    //短信验证码接口
    public function sms()
    {
        header("Content-type:text/html; charset=UTF-8");
//获取手机号
        $mobile = I('post.mobile');

        $temp=

//获取验证码
        $send_code = I('post.send_code');
        $uname=I('post.uname');

        //验证用户名称是否正确
        $D=M('user');
        $data=$D->field('username,mobile')->where('username="'.$uname.'"')->find();

        if(empty($data))
        {
            echo 1;
            die();
        }
        if(empty($data['mobile']))
        {
            echo 5;//帐户没有绑定手机
            die();
        }
        if($mobile!=$data['mobile'])
        {
            echo 6;//帐户没有绑定手机
            die();
        }


        vendor('smsapi');

        //用户账号
        $uid = 'xxxs';
        //MD5密码
        $pwd = '135812984444';

        $api = new \SmsApi($uid,$pwd);


        $contentParam = array(
            'code'		=> $api->randNumber(),
            'username'	=> '您好',
            'name'=>$uname
        );

//变量模板ID
        //$template = '394713';
        $template=I('post.template');


//发送变量模板短信
        $result = $api->send($mobile,$contentParam,$template);

        if($result['stat']=='100')
        {

            session('mobile',$mobile);
            session('mobile_code', $contentParam['code']);
            echo 4;
             die();
        }
        else
        {

            echo 7;
            die();
        }



    }
    //下一步
    public function dosms()
    {
        $mobile = I('post.mobile');
//获取验证码

        $uname=I('post.uname');
        $mobile_code=I('post.mobile_code');
        //验证用户名称是否正确
        $D=M('user');
        $data=$D->field('username,mobile')->where('username="'.$uname.'"')->find();
        //帐户为空
        if(empty($data))
        {
            echo 1;
            die();
        }
        //没有绑定手机号
        if(empty($data['mobile']))
        {
            echo 2;//帐户没有绑定手机
            die();
        }
        //输入手机号与绑定号不符
        if($mobile!=$data['mobile'])
        {
            echo 3;//帐户没有绑定手机
            die();
        }
        //输入验证码不正确
        if($mobile_code!=session('mobile_code'))
        {
            echo 4;//
            die();
        }

    }
    //重置登录密码
    public function resetpwd()
    {
        $mobile = I('post.mobile');
        $uname=I('post.uname');
        $mobile_code=I('post.mobile_code');
        $newpwd=I('post.newpwd');
        //验证用户名称是否正确
        $D=M('user');
        $data=$D->field('username,mobile')->where('username="'.$uname.'"')->find();
        //帐户为空
        if(empty($data))
        {
            echo 1;
            die();
        }
        //没有绑定手机号
        if(empty($data['mobile']))
        {
            echo 2;//帐户没有绑定手机
            die();
        }
        //输入手机号与绑定号不符
        if($mobile!=$data['mobile'])
        {
            echo 3;//帐户没有绑定手机
            die();
        }
        //输入验证码不正确
        if($mobile_code!=session('mobile_code'))
        {
            echo 4;//
            die();
        }

        $arr=array('password'=>md5($newpwd));
        $D->where('username="'.$uname.'"')->save($arr);
        echo'success';
        die();

    }
    //重置支付密码
    public function resetpaypwd()
    {
        $mobile = I('post.mobile');
        $uname=I('post.uname');
        $mobile_code=I('post.mobile_code');
        $newpwd=I('post.newpwd');
        //验证用户名称是否正确
        $D=M('user');
        $data=$D->field('username,mobile')->where('username="'.$uname.'"')->find();
        //帐户为空
        if(empty($data))
        {
            echo 1;
            die();
        }
        //没有绑定手机号
        if(empty($data['mobile']))
        {
            echo 2;//帐户没有绑定手机
            die();
        }
        //输入手机号与绑定号不符
        if($mobile!=$data['mobile'])
        {
            echo 3;//帐户没有绑定手机
            die();
        }
        //输入验证码不正确
        if($mobile_code!=session('mobile_code'))
        {
            echo 4;//
            die();
        }

        $arr=array('paypassword'=>md5($newpwd));
        $D->where('username="'.$uname.'"')->save($arr);
        echo'success';
        die();

    }



    private function Post($curlPost,$url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $return_str = curl_exec($curl);
        curl_close($curl);
        return $return_str;
    }

    //将 xml数据转换为数组格式。
    private function xml_to_array($xml){
        $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
        if(preg_match_all($reg, $xml, $matches)){
            $count = count($matches[0]);
            for($i = 0; $i < $count; $i++){
                $subxml= $matches[2][$i];
                $key = $matches[1][$i];
                if(preg_match( $reg, $subxml )){
                    $arr[$key] = $this->xml_to_array( $subxml );
                }else{
                    $arr[$key] = $subxml;
                }
            }
        }
        return $arr;
    }

    //random() 函数返回随机整数。
    private function random($length = 6 , $numeric = 0) {
        PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
        if($numeric) {
            $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
        } else {
            $hash = '';
            $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
            $max = strlen($chars) - 1;
            for($i = 0; $i < $length; $i++) {
                $hash .= $chars[mt_rand(0, $max)];
            }
        }
        return $hash;
    }
    public function reg()
    {
        header("Content-Type: text/html;charset=utf-8");
        $tusername=I('get.id');

        $D=M('user');
        $data=$D->field('tusername')->where('username="'.$tusername.'"')->find();
        if(empty($data))
        {
            echo("<script>alert('推荐人不存在！请输入正确的网址！');</script>");
            die();
        }


        $this->assign('tusername',$tusername);

        $this->display();
    }
    public function doreg()
    {


        $username = I('post.username');
        $password = md5(I('post.password'));
        $paypassword = md5(I('post.paypassword'));
        $tusername = I('post.tusername');
        $realname = I('post.realname');
        $mobile = I('post.mobile');
        $mobile_code=I('post.mobile_code');

        $paper = I('post.paper');
        $bankname = I('post.bankname');
        $bank = I('post.bank');
        $bankcode = I('post.bankcode');
        $weixin = I('post.weixin');
        $alipay = I('post.alipay');
        $address = I('post.address');



        $D = M('user');

        $createtime = time();


        //取得推荐人ＩＤ
        $data1 = $D->where('username="' . $username . '"')->find();
        if (!empty($data1)) {
            echo 2;//用户名已经存在，
            die();
        }

        $pdata = $D->where('username="' . $tusername . '"')->find();
        if (empty($pdata)) {
            echo 3;//推荐人不存在，
            die();
        }
        //判断手机号码
        $data2 = $D->where('mobile="' . $mobile . '"')->find();
        if (!empty($data2)) {
            echo 4;//手机号码已经存在，
            die();
        }
        //判断手机号码
        $data3 = $D->where('paper="' . $paper . '"')->find();
        if (!empty($data3)) {
            echo 6;//手机号码已经存在，
            die();
        }
        

        //输入验证码不正确
        if($mobile_code!=session('mobile_code'))
        {
            echo 5;//
            die();
        }


        $arr=array(
            'username'=>$username,
            'password'=>$password,
            'paypassword'=>$paypassword,
            'tusername'=>$tusername,
            'realname'=>$realname,
            'mobile'=>$mobile,
            'createtime'=>$createtime,
            'gotegary'=>0,
            'status'=>0,
            'paper'=>$paper,
            'bankname'=>$bankname,
            'bank'=>$bank,
            'bankcode'=>$bankcode,
            'weixin'=>$weixin,
            'alipay'=>$alipay,
            'address'=>$address,

        );



        $id=$D->add($arr);//添加会员
        $path=$pdata['path'].$id.',';
        $number=$this->donumber($id);
        $arr=array('path'=>$path,
            'number'=>$number,
        );
        $D->where('id='.$id)->save($arr);


        $I=M('integral');
        $arri=array(
            'userid'=>$id,
            'integral1'=>0,
            'integral2'=>0,
            'integral3'=>0,
            'integral4'=>0,
            'integral5'=>0,
        );
        $I->add($arri);//加入积分表
        echo 1;
        die();


    }
    //生成会员编号
    private function donumber($id)
    {

        $number='A'.str_pad($id,9,"0",STR_PAD_LEFT);
        return $number;
    }

    public function regsms()
    {
        header("Content-type:text/html; charset=UTF-8");
//获取手机号
        $mobile = I('post.mobile');
//获取验证码
        $send_code = I('post.send_code');

        //验证用户名称是否正确
        $D=M('user');
        $data=$D->field('mobile')->where('mobile="'.$mobile.'"')->find();

        if(!empty($data))
        {
            echo 1;
            die();
        }

        

        vendor('smsapi');

        //用户账号
        $uid = 'xxxs';
        //MD5密码
        $pwd = '135812984444';

        $api = new \SmsApi($uid,$pwd);


        $contentParam = array(
            'code'		=> $api->randNumber(),
            'username'	=> '您好'
        );

//变量模板ID
        $template = '100005';

//发送变量模板短信
        $result = $api->send($mobile,$contentParam,$template);

        if($result['stat']=='100')
        {

            session('mobile',$mobile);
            session('mobile_code', $contentParam['code']);
            echo 4;
            die();
        }
        else
        {

            echo 7;
            die();
        }



    }

    //发送短信
    public function sentsms()
    {
        header("Content-Type: text/html;charset=utf-8");

        vendor('smsapi');

        //用户账号
        $uid = 'xxxs';
        //MD5密码
        $pwd = '135812984444';

        $api = new \SmsApi($uid,$pwd);


        $mobile = '18665594829';

//短信内容参数
        $contentParam = array(
            'code'		=> $api->randNumber(),
            'username'	=> '您好'
        );

//变量模板ID
        $template = '100005';

//发送变量模板短信
        $result = $api->send($mobile,$contentParam,$template);

        if($result['stat']=='100')
        {
            echo '发送成功';
        }
        else
        {
            echo '发送失败:'.$result['stat'].'('.$result['message'].')';
        }



    }


    //修改安全密码
    public function dopaysms()
    {
        $mobile = I('post.mobile');
//获取验证码

        $uname=I('post.uname');
        $mobile_code=I('post.mobile_code');
        //验证用户名称是否正确
        $D=M('user');
        $data=$D->field('username,mobile')->where('username="'.$uname.'"')->find();
        //帐户为空
        if(empty($data))
        {
            echo 1;
            die();
        }
        //没有绑定手机号
        if(empty($data['mobile']))
        {
            echo 2;//帐户没有绑定手机
            die();
        }
        //输入手机号与绑定号不符
        if($mobile!=$data['mobile'])
        {
            echo 3;//帐户没有绑定手机
            die();
        }
        //输入验证码不正确
        if($mobile_code!=session('mobile_code'))
        {
            echo 4;//
            die();
        }

    }
    //超过12小时不打款，冻结帐户
    private function offuser()
    {
        $TG=M('toget');
        $T=M('tohelp');
        $U=M('user');
        $I=M('integral');
        $G=M('gethelp');
        $tdata=$T->where('status=1')->select();
        $time=time();
        $hour12=3600*12;//12小时
        if(!empty($tdata))
        {
           foreach($tdata as $vo)
          {
            $lasttime=$time-$vo['begintime'];

            if($lasttime>$hour12)
            {
                //冻结帐户
                $arr=array('status'=>3);
                $U->where('id='.$vo['userid'])->save($arr);




                //得到帮助返回匹配例表


                    $data=$TG->where('toid='.$vo['id'].' and status=1')->select();

                    foreach($data as $vo1)
                    {
                        $arr=array('status'=>0);
                        $G->where('id='.$vo1['getid'])->save($arr);
                    }
                    $TG->where('toid='.$vo['id'].' and status=1')->delete();
                    $T->where('id='.$vo['id'].' and status=1')->delete();
             }




            }
        }


    }


}